package ztc.service;

import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

public class QRCodeMaker {
    private  Color foreground = Color.white;
    private  Color background = Color.black;

    /**
     * 默认构造器
     */
    public QRCodeMaker() {
    }

    /**
     * 构造器.
     * 设置颜色
     * @param foreground　前景色
     * @param background　背景色
     */
    public QRCodeMaker(Color foreground,Color background){
        this.foreground=foreground;
        this.background=background;
    }

    /**
     * BitMatrix转到BufferedImage.
     * @param bitMatrix 编码过得文字
     * @return
     * 返回bufferedImage
     */
    public BufferedImage toBufferedImage(BitMatrix bitMatrix){
        int width=bitMatrix.getWidth();
        int hight=bitMatrix.getHeight();
        BufferedImage image=new BufferedImage(width,hight,BufferedImage.TYPE_INT_RGB);
        for(int i=0;i<width;i++){
            for(int j=0;j<hight;j++){
                image.setRGB(i,j,bitMatrix.get(i,j)?background.getRGB():foreground.getRGB());
            }
        }
        return image;
    }

    /**
     * 写到输出流中.
     * @param bitMatrix　编码过得文字
     * @param outputStream　输出流
     * @param format　图片格式
     * @param application 服务器application对象
     */
    public void writeToStream(BitMatrix bitMatrix,OutputStream outputStream,String format,ServletContext application,HttpSession session){
        BufferedImage img=toBufferedImage(bitMatrix);
        try {
            ImageIO.write(img,format,outputStream);
            outputStream.close();
        } catch (IOException e) {
            QRStatus.rollback(application,session);
            e.printStackTrace();
        }
    }

}
